package com.killer.handler;

import com.alibaba.fastjson.JSON;
import com.killer.rpc.RpcRequest;
import com.killer.util.SpringContextUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

/**
 * @author ：Killer
 * @date ：Created in 20-11-27 上午10:41
 * @description：${description}
 * @modified By：
 * @version: version
 */
public class RpcServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof RpcRequest) {
            RpcRequest rpcRequest=(RpcRequest)msg;
            //获取调用的类名
            String className=rpcRequest.getClassName();
            //获取对应的serviceBean
            Class clazz = Class.forName(className);
            Object serviceBean = SpringContextUtil.getBean(clazz);
            //获取调用的方法名
            String methodName=rpcRequest.getMethodName();
            //获取对应的方法
            Method method = clazz.getDeclaredMethod(methodName, rpcRequest.getParamTypes());
            Object[] parseParams =rpcRequest.getParams()==null?null:new Object[rpcRequest.getParams().length];
            if (parseParams != null) {
                for(int i=0;i<parseParams.length;i++) {
                    //重新序列化再重新反序列化
                    String json = JSON.toJSONString(rpcRequest.getParams()[i]);
                    parseParams[i] = JSON.parseObject(json, rpcRequest.getParamTypes()[i]);
                }
            }

            Object result = method.invoke(serviceBean, parseParams);
            System.out.println(result);
            //将返回结果写回去给客户端
            ctx.writeAndFlush(result);
        }
    }

}
